package com.example.paper1024.controller;

import com.example.paper1024.entity.Paper;
import com.example.paper1024.imply.PaperService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@CrossOrigin(origins = "*", allowedHeaders = "*", methods = {RequestMethod.GET, RequestMethod.POST, RequestMethod.DELETE, RequestMethod.PUT})
@RestController
@RequestMapping("/paper")
public class PaperController {

    @Autowired
    private PaperService paperService;

    // 新增论文，返回新增的Paper对象
    @PostMapping("/add")
    public ResponseEntity<Paper> addPaper(@RequestBody Paper paper) {
        try {
            Paper addedPaper = paperService.addPaperAndReturn(paper);
            return ResponseEntity.ok(addedPaper);
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(null);
        }
    }

    // 获取所有论文，按id降序排序
    @GetMapping("/paperList")
    public ResponseEntity<List<Paper>> paperList() {
        try {
            List<Paper> paperList = paperService.getAllPapers();
            return ResponseEntity.ok(paperList);
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(null);
        }
    }

    // 根据 ID 获取论文
    @GetMapping("/getPaperById")
    public ResponseEntity<Paper> getPaperById(@RequestParam("id") int id) {
        try {
            Paper paper = paperService.getPaperById(id);
            if (paper != null) {
                return ResponseEntity.ok(paper);
            } else {
                return ResponseEntity.status(404).body(null);
            }
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(null);
        }
    }

    // 更新论文
    @PutMapping("/update")
    public ResponseEntity<String> updatePaper(@RequestBody Paper paper) {
        try {
            int result = paperService.updatePaper(paper);
            if (result == 1) {
                return ResponseEntity.ok("更新成功");
            } else {
                return ResponseEntity.status(500).body("更新失败");
            }
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("更新异常: " + e.getMessage());
        }
    }

    // 删除论文
    @DeleteMapping("/delete")
    public ResponseEntity<String> deletePaper(@RequestParam("id") int id) {
        try {
            int result = paperService.deletePaper(id);
            if (result == 1) {
                return ResponseEntity.ok("删除成功");
            } else {
                return ResponseEntity.status(500).body("删除失败");
            }
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("删除异常: " + e.getMessage());
        }
    }
}
